package com.jlnk.stockdemo.activity;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;
import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.adapter.ViewPagerAdapter;
import com.jlnk.stockdemo.fragment.HotFragment;
import com.jlnk.stockdemo.fragment.MineFragment;
import com.jlnk.stockdemo.fragment.NewsFragment;
import com.jlnk.stockdemo.utils.Constants;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private MineFragment mineFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tabLayout);
        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);
        initTabIcon(tabLayout);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        mineFragment = new MineFragment();
        adapter.addFragment(new NewsFragment(), "首页");
        adapter.addFragment(new HotFragment(), "热点");
        adapter.addFragment(mineFragment, "我的");
        viewPager.setAdapter(adapter);
    }

    private void initTabIcon(TabLayout tabLayout) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab == null) {
                break;
            }
            switch (i) {
                case 0:
                    tab.setIcon(R.drawable.home);
                    break;
                case 1:
                    tab.setIcon(R.drawable.hot);
                    break;
                case 2:
                    tab.setIcon(R.drawable.mine);
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.MINE_FRAGMENT_REQUEST_CODE && resultCode == RESULT_OK) {
            mineFragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}
